package com.jwx.mycar.controller;


import com.jwx.mycar.entity.vo.ResultVo;
import com.jwx.mycar.mapper.UserMapper;
import com.jwx.mycar.service.UserService;
import com.jwx.mycar.utils.ResultVOUtil;
import com.jwx.mycar.utils.VerifyUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.OutputStream;

@RestController
/**
@ResponseBody
@Controller
*/
/**
 * Description :用户管理层controller
 * @auther:jwx
 */

@Api(tags = "用户")
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;
    @Autowired
    UserMapper userMapper;

    @Autowired
    JavaMailSender jms;

    @Autowired
    ResultVOUtil resultVOUtil;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 登录接口
     *
     * @param email 邮箱（账号）
     * @param password 密码
     */
    @PostMapping(value = "/login")
    @ApiOperation(value = "用户登录", notes = "根据邮箱（账号）和密码登录")
    @ApiImplicitParams( {@ApiImplicitParam(name = "email", value = "邮箱（账号）", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
    })
    public ResultVo login(@RequestParam("email") String email, @RequestParam("password") String password, HttpServletResponse response, HttpServletRequest request)throws Exception{
        System.out.println(request.getSession().getId());
       return userService.login(email,password,request,response);
    }
    /**
     *
     * @description:修改密码
     * @param null
     * @return:
     * @author: jwx
     * @time: 2019/12/2 16:10
     */

    @PostMapping(value = "/changePassword" ,params = {"password","newPassword","email"})
    @ApiOperation(value = "修改密码")
    public  ResultVo resetPassword(@RequestParam("password") String password,@RequestParam("newPassword") String newPassword,@RequestParam("email") String email){
        boolean success = userService.changePassword(password,newPassword,email);
        if (success){
            return resultVOUtil.success("修改成功");
        }
        else {
            return resultVOUtil.fail("邮箱或密码错误");
        }

    }


    /**
     * 注册用户
     * @param username
     * @param password
     * @param email
     * @param code
     * @param request
     * @return
     * @throws Exception
     */

    @PostMapping(value = "/register")
    @ApiOperation(value = "用户注册",notes = "根据用户名、邮箱和密码注册")
    @ApiImplicitParams( {@ApiImplicitParam(name = "username", value = "用户名", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "password", value = "密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query"),
    })
    public ResultVo register(@RequestParam("username") String username, @RequestParam("password") String password,@RequestParam("email") String email,@RequestParam("code") String code,HttpServletRequest request)throws Exception{
        return userService.register(username,password,email,code,request);
    }

    /**
     * 发送邮件验证码
     */

    @PostMapping("/sendEmail")
    @ApiOperation(value = "发送邮件验证码",notes = "根据邮箱发送邮箱验证码")
    @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "query")
    public ResultVo send(@RequestParam("email") String email,HttpServletRequest request) {
        boolean isExist = userMapper.emailExist(email);
        try {
            if (!isExist) {
                return resultVOUtil.fail("该用户不存在，请检查邮箱是否正确");
            } else {
                HttpSession session = request.getSession();
                String resetCode = VerifyUtil.createEmailCode();
                session.setAttribute("resetCode", resetCode);
                System.out.println(session.getId());
                //建立邮件消息
                SimpleMailMessage mainMessage = new SimpleMailMessage();
                //发送者
                mainMessage.setFrom("mycartest@126.com");
                //接收者
                mainMessage.setTo(email);
                //发送的标题
                mainMessage.setSubject("重置密码验证码");
                //发送的内容
                mainMessage.setText("【mycar】验证码：" + resetCode + ",您正在使用邮件验证找回密码，该验证码仅用于身份验证，请勿泄露给他人使用。");
                jms.send(mainMessage);
                System.out.println("发送成功");
                return resultVOUtil.success();
            }
        }
        catch (Exception e){
            e.printStackTrace();
            return resultVOUtil.unkonwError();
        }
    }
    /**
     *找回密码，调用该接口前应该先调用sendMail接口
     * @param newPassword,email,
     * @return
     */
    @ApiOperation(value = "找回密码",notes = "根据用户名邮箱重置密码")
    @ApiImplicitParams( {@ApiImplicitParam(name = "newPassword", value = "新密码", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "query"),
            @ApiImplicitParam(name = "code", value = "验证码", required = true, dataType = "String", paramType = "query")
    })
    @GetMapping("/resetPassword")
    public ResultVo send( @RequestParam("newPassword") String newPassword,@RequestParam("email") String email,@RequestParam("code") String code,HttpServletRequest request, HttpServletResponse response){
        return userService.resetPassword(newPassword,email,code,request,response);
    }
    /**
     * 生成图片验证码
     */
    @ApiOperation("生成验证码")
    @ApiImplicitParam(name = "email", value = "邮箱", required = true, dataType = "String", paramType = "query")
    @GetMapping("/getCode")
    public void getCode(HttpServletResponse response, HttpServletRequest request,@RequestParam("email") String email) throws Exception{
        HttpSession session=request.getSession();
        //利用图片工具生成图片
        //第一个参数是生成的验证码，第二个参数是生成的图片
        Object[] objs = VerifyUtil.createImage();
        //将验证码存入Session
//        session.setAttribute("imageCode",objs[0]);
        //将验证码存入Cookie
       // Cookie cookie=new Cookie("sessionId",objs[0].toString());
        //将图片输出给浏览器
        //将验证码存入redis缓存
        String[] sArray=email.split("\\s");
        String reallKey=sArray[0];
        redisTemplate.opsForValue().set(reallKey,objs[0].toString());
        String imageCode = redisTemplate.opsForValue().get(email);
//        System.out.println("生成主键email："+email);
//        System.out.println("生成value"+imageCode);
        BufferedImage image = (BufferedImage) objs[1];
        response.setContentType("image/png");
        OutputStream os = response.getOutputStream();
        ImageIO.write(image, "png", os);
    }

    @ApiOperation("获取用户点赞总数")
    @GetMapping("/getUpCount")
    public ResultVo getUpCount(HttpServletRequest request){
       int count =  userService.getAllUpCount(request);
       return resultVOUtil.success(count);
    }



}
